package com.stu.dcxy.juc;

import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;

/**
 * @Author: MI
 * @Date: 2022/3/10/22:06
 * @Description:
 */
class MyVar {
    public volatile Boolean isInit = Boolean.FALSE;
    AtomicReferenceFieldUpdater<MyVar, Boolean> FileUpdater = AtomicReferenceFieldUpdater.newUpdater(MyVar.class, Boolean.class, "isInit");

    public void init() {
        if (FileUpdater.compareAndSet(this, Boolean.FALSE, Boolean.TRUE)) {
            System.out.println(Thread.currentThread().getName() + "\t start in");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
            }
            System.out.println(Thread.currentThread().getName() + "\t end in");
        } else {
            System.out.println(Thread.currentThread().getName() + "\t 失败");
        }

    }
}

/**
 * 多线程并发调用一个类的初始化，如果未被初始化，将执行初始化工作，要求只能初始化一次
 */
public class AtomicReferenceFieldUpdaterDemo {
    public static void main(String[] args) {
        MyVar myVar = new MyVar();
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                myVar.init();
            }).start();
        }
        try {
            TimeUnit.SECONDS.sleep(ThreadLocalRandom.current().nextInt(5) + 1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
